/***************************************************
 ** @Desc : This file for 加密、解密方法
 ** @Time : 2018.12.28 14:10
 ** @Author : Joker
 ** @File : encryption
 ** @Last Modified by : Joker
 ** @Last Modified time: 2019-4-8 09:54:58
 ** @Software: GoLand
****************************************************/
package utils

import (
	"crypto"
	"crypto/md5"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"crypto/x509"
	"encoding/base64"
	"encoding/hex"
	"encoding/pem"
	"errors"
	"strings"
)

type Encrypt struct{}

//将字符串加密成 md5
func (*Encrypt) EncodeMd5(buf []byte) string {
	hash := md5.New()
	hash.Write(buf)
	return hex.EncodeToString(hash.Sum(nil))
}

//RSA加密
func (*Encrypt) RsaEncrypto(origData, publicKey []byte) ([]byte, error) {
	block, _ := pem.Decode(publicKey) //将密钥解析成公钥实例
	if block == nil {
		return nil, errors.New("RsaEncrypto public key is error")
	}
	pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes) //解析返回的Block指针实例
	if err != nil {
		return nil, err
	}
	key := pubInterface.(*rsa.PublicKey)
	return rsa.EncryptPKCS1v15(rand.Reader, key, origData)
}

//RSA解密
func (*Encrypt) RsaDecrypto(keyText, privateKey []byte) ([]byte, error) {
	block, _ := pem.Decode(privateKey) //将密钥解析成私钥实例
	if block == nil {
		return nil, errors.New("RsaDecrypto private key is error")
	}
	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes) //解析返回的block指针实例
	if err != nil {
		return nil, err
	}
	return rsa.DecryptPKCS1v15(rand.Reader, priv, keyText)
}

// SHA256WithRSA生成签名
func (*Encrypt) SHA256WithRSAToSign(originalData, privateKey []byte) ([]byte, error) {
	block, _ := pem.Decode(privateKey) //将密钥解析成私钥实例
	if block == nil {
		return nil, errors.New("SHA256WithRSAToSign private key is error")
	}
	privt, err := x509.ParsePKCS1PrivateKey(block.Bytes) //解析返回的block指针实例
	if err != nil {
		return nil, err
	}

	hash := sha256.New()
	hash.Write([]byte(originalData))
	return rsa.SignPKCS1v15(rand.Reader, privt, crypto.SHA256, hash.Sum(nil)[:])
}

//base64编码
func (*Encrypt) Base64Encode(raw []byte) string {
	t := base64.StdEncoding.EncodeToString(raw)
	t = strings.TrimSpace(t)
	t = strings.Replace(t, "\r", "", -1)
	t = strings.Replace(t, "\n", "", -1)
	t = strings.Replace(t, "\n\r", "", -1)
	t = strings.Replace(t, "\r\n", "", -1)
	return t
}

//base64解码
func (*Encrypt) Base64Decode(raw string) ([]byte, error) {
	return base64.StdEncoding.DecodeString(raw)
}
